package com.graduation_design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.entity.SysRole;
import com.graduation_design.entity.SysRoleMenu;
import com.graduation_design.entity.SysUserRole;
import com.graduation_design.service.SysRoleMenuService;
import com.graduation_design.service.SysRoleService;
import com.graduation_design.mapper.SysRoleMapper;
import com.graduation_design.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author 从南
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-02-16 18:15:59
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService{

    @Resource
    SysRoleMenuService sysRoleMenuService;

    @Resource
    SysUserRoleService sysUserRoleService;

    /**
     * 把对应的角色信息查出来
     */
    @Override
    public List<SysRole> listRolesByUserId(Long userId) {
        return this.list(new QueryWrapper<SysRole>()
                .inSql("id", "select role_id from sys_user_role where user_id = " + userId));
    }

    /**
     * 删除角色信息
     * 需要把角色关联的中间表，比如用户-角色、角色-权限这两个中间表删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBath(Long... ids) {
        this.removeByIds(Arrays.asList(ids));

        // 同步删除关联表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>()
                .in("role_id", Arrays.asList(ids))
        );
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>()
                .in("role_id", Arrays.asList(ids))
        );
    }

    /**
     * 分配权限
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void perm(Long roleId, Long... menuIds) {
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();

        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);

            sysRoleMenus.add(roleMenu);
        });

        // 先删除原来的
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>()
                .eq("role_id", roleId)
        );
        sysRoleMenuService.saveBatch(sysRoleMenus);
    }
}




